<?php
namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

/**
 * Redis调试命令
 */
class DebugRedis extends Command
{
    protected function configure()
    {
        $this->setName('debug:redis')
            ->setDescription('调试CLI环境下的Redis配置');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln("=== CLI环境Redis调试 ===");
        
        // 1. 检查PHP环境
        $output->writeln("PHP版本: " . PHP_VERSION);
        $output->writeln("SAPI: " . php_sapi_name());
        $output->writeln("PHP配置文件: " . php_ini_loaded_file());
        
        // 2. 检查Redis扩展
        $redisLoaded = extension_loaded('redis');
        $output->writeln("Redis扩展: " . ($redisLoaded ? '已加载' : '未加载'));
        if ($redisLoaded) {
            $output->writeln("Redis扩展版本: " . phpversion('redis'));
        }
        
        // 3. 检查缓存配置
        $cacheConfig = config('cache');
        $output->writeln("缓存配置: " . json_encode($cacheConfig, JSON_UNESCAPED_UNICODE));
        
        // 4. 测试原生Redis连接
        if ($redisLoaded) {
            try {
                $redis = new \Redis();
                $redis->connect('127.0.0.1', 6379);
                if (!empty('qazEdc')) {
                    $redis->auth('qazEdc');
                }
                $redis->set('cli_test_key', 'cli_test_value');
                $value = $redis->get('cli_test_key');
                $redis->del('cli_test_key');
                $redis->close();
                $output->writeln("原生Redis测试: 成功 (值: {$value})");
            } catch (\Throwable $e) {
                $output->writeln("原生Redis测试: 失败 - " . $e->getMessage());
            }
        }
        
        // 5. 测试ThinkPHP Cache
        try {
            Cache::set('cli_tp_test', 'cli_tp_value', 60);
            $value = Cache::get('cli_tp_test');
            Cache::rm('cli_tp_test');
            $output->writeln("ThinkPHP Cache测试: 成功 (值: {$value})");
        } catch (\Throwable $e) {
            $output->writeln("ThinkPHP Cache测试: 失败 - " . $e->getMessage());
        }
        
        // 6. 测试cache助手函数
        try {
            cache('cli_helper_test', 'cli_helper_value', 60);
            $value = cache('cli_helper_test');
            cache('cli_helper_test', null);
            $output->writeln("cache()助手函数测试: 成功 (值: {$value})");
        } catch (\Throwable $e) {
            $output->writeln("cache()助手函数测试: 失败 - " . $e->getMessage());
        }
        
        // 7. 测试MqttMessageHandler
        try {
            $handler = new \app\service\MqttMessageHandler();
            $result = $handler->forceCheckImeiExists('cli_test_imei');
            $output->writeln("MqttMessageHandler测试: 成功 (结果: " . ($result ? '存在' : '不存在') . ")");
        } catch (\Throwable $e) {
            $output->writeln("MqttMessageHandler测试: 失败 - " . $e->getMessage());
        }
        
        $output->writeln("=== 调试完成 ===");
    }
}
